package com.eryos.android.cigarettecounter.widget;

import com.eryos.android.cigarettecounter.database.CigaretteDatabase;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2012 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

public class CigaretteCounterWidger extends AppWidgetProvider {
	
	private static final String LOG_TAG = "CigaretteCounterWidger";

	/**
	 * Method call for ACTION_APPWIDGET_UPDATE intents
	 */
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		Log.w(LOG_TAG, "onUpdate method called");
		// Get all ids
		ComponentName thisWidget = new ComponentName(context, CigaretteCounterWidger.class);
		int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
		
		// Build the intent to call the service
		Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

		// Update the widgets via the service
		context.startService(intent);
	}
	
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.w(LOG_TAG, "onReceive method called : "+intent.getAction());
		
		// If Intent is dedicated to DB action
		if (intent != null && intent.getAction() != null && intent.getAction().equalsIgnoreCase(UpdateWidgetService.INCREASE_ACTION) ) {
			Log.i(LOG_TAG, "Increase action ...");

			// Open DB and insert new cigarette record
			CigaretteDatabase db = CigaretteDatabase.getInstance(context);
	    	db.open();
			if ( db != null ){
				db.insertCurrentTimestamp("", 0);
				Log.d(LOG_TAG, "insert DB OK");
				//db.close();
			}
			
			// Update all widgets
			updateAllWidgets(context);

		}else {
			
			// If it's another intent, follow the 'normal' process
			super.onReceive(context, intent);
		}
	}
	
	
	/**
	 * Method used to create and send an Update Intent for all widgets
	 * @param context
	 */
	public static void updateAllWidgets(Context context){
	
		// Prepare a new intent to refresh widgets
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		ComponentName thisWidget = new ComponentName(context, CigaretteCounterWidger.class);
		int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
		
		Intent intentUpdate = new Intent(context, CigaretteCounterWidger.class);
		intentUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		intentUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

		try {
			PendingIntent.getBroadcast(context, 0, intentUpdate, PendingIntent.FLAG_UPDATE_CURRENT).send();
		} catch (CanceledException e) {
			e.printStackTrace();
		}
	}
   
   
	/**
	 * Method used to create an intent that will be used when clicking on widget (or widget component)
	 * @param allWidgetIds
	 * @return PendingIntent ready to be attach with setOnClickPendingIntent method
	 */
	public static PendingIntent createClickPendingIntent(Context ctx, int[] allWidgetIds){
		// Register an onClickListener
		Intent clickIntent = new Intent(ctx, CigaretteCounterWidger.class);

		clickIntent.setAction(UpdateWidgetService.INCREASE_ACTION);
		clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

		PendingIntent pendingIntent = PendingIntent.getBroadcast( ctx, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		return pendingIntent;
	}
   
}
